package tech.dongliang.system.controller;


import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import tech.dongliang.common.controller.CommonController;
import tech.dongliang.common.enums.EBizError;
import tech.dongliang.common.response.CommonResponse;
import tech.dongliang.common.response.ErrorData;
import tech.dongliang.system.model.SysDept;
import tech.dongliang.system.model.SysRole;
import tech.dongliang.system.model.SysUser;
import tech.dongliang.system.service.ISysDeptService;
import tech.dongliang.system.service.ISysRoleService;
import tech.dongliang.system.service.ISysUserRoleService;
import tech.dongliang.system.service.ISysUserService;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xdzhang
 * @since 2019-01-18
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends CommonController {
    private String prefix = "system/user";
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserRoleService userRoleService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysDeptService deptService;

    @GetMapping()
    String menu() throws Exception {
        return prefix + "/list";
    }

    @ResponseBody
    @GetMapping("/list")
    public CommonResponse<IPage<SysUser>> list(@RequestParam(value = "page", required = false, defaultValue = "1") Long page,
                                               @RequestParam(value = "name", required = false) String name) throws Exception {
        IPage<SysUser> pager = new Page<>();
        pager.setPages(page);
        QueryWrapper<SysUser> query = new QueryWrapper();
        if (StringUtils.isNotBlank(name)) {
            query.eq("name", name).or().eq("username", name);
        }
        pager = sysUserService.page(pager, query);
        return CommonResponse.success(pager);
    }

    @GetMapping("/add")
    public String add(Model model) throws Exception {
        List<SysRole> role = roleService.list();
        model.addAttribute("role", role);
        model.addAttribute("deptName", "总部门");
        return prefix + "/add";
    }

    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Integer userId, Model model) throws Exception {
        SysUser sysUser = sysUserService.getById(userId);
        List<Integer> roleIds = userRoleService.getUserRoleId(userId);
        List<SysRole> role = roleService.list();
        SysDept sysDept = deptService.getById(sysUser.getDeptId());
        sysUser.setRoleIds(roleIds);
        model.addAttribute("sysUser", sysUser);
        model.addAttribute("role", role);
        model.addAttribute("sysDept", sysDept);
        return prefix + "/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    public CommonResponse<Boolean> save(@Valid SysUser sysUser, BindingResult result) throws Exception {
        if (!sysUser.getPassword().equals(sysUser.getPassword2())) {
            return CommonResponse.error(new ErrorData(EBizError.PASSWORD_ERROR));
        }
        sysUser.setStatus(1);
        sysUser.setCreateTime(System.currentTimeMillis());
        sysUser.setPassword(DigestUtil.md5Hex(sysUser.getPassword()));
        if (sysUserService.save(sysUser)) {
            return CommonResponse.success(true);
        }
        return CommonResponse.error(new ErrorData(EBizError.UNKNOWE_ERROR));
    }

    /**
     * 修改
     */
    @ResponseBody
    @PostMapping("/update")
    public CommonResponse<Boolean> update(@Valid SysUser sysUser, BindingResult result) throws Exception {
        if (!sysUser.getPassword().equals(sysUser.getPassword2())) {
            return CommonResponse.error(new ErrorData(EBizError.PASSWORD_ERROR));
        }
        SysUser old = sysUserService.getById(sysUser.getId());
        if (old == null) {
            return CommonResponse.error(new ErrorData(EBizError.PARAMETER_VALIDATION_ERROR));
        } else {
            if (!old.getPassword().equals(sysUser.getPassword())) {
                sysUser.setPassword(DigestUtil.md5Hex(sysUser.getPassword()));
            }
        }
        sysUser.setModifyTime(System.currentTimeMillis());
        if (sysUserService.updateById(sysUser)) {
            return CommonResponse.success(true);
        }
        return CommonResponse.error(new ErrorData(EBizError.UNKNOWE_ERROR));
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    public CommonResponse<Boolean> remove(Integer userId) throws Exception {
        if (sysUserService.removeById(userId)) {
            return CommonResponse.success(true);
        }
        return CommonResponse.error(new ErrorData(EBizError.UNKNOWE_ERROR));
    }

    /**
     * 删除
     */
    @PostMapping("/changeStatus")
    @ResponseBody
    public CommonResponse<Boolean> changeStatus(Integer userId, Integer status) throws Exception {
        if (sysUserService.changeStatus(userId, status)) {
            return CommonResponse.success(true);
        }
        return CommonResponse.error(new ErrorData(EBizError.UNKNOWE_ERROR));
    }

}
